import * as uuid from 'uuid';
import { type FC, useRef, useEffect } from 'react';
import { useMemoizedFn, useSafeState } from 'ahooks';
import ChatSender from '../ChatSender';
import ChatHistory from '../ChatHistory';
import { useSocket } from '@/components/Socket/hooks';
import type { ChatHistoryType, ChatsProps } from './types';
import styles from './styles.module.less';

const defaultHistory: ChatHistoryType[] = [
  {
    id: uuid.v4(),
    isDone: true,
    messages: [{
      id: uuid.v4(),
      type: 'text',
      visible: true,
      prinit: false,
      text: 'Ask me whatever you want to know...'
    }]
  }
];

const Chats: FC<ChatsProps> = (props) => {
  const { defaultHistories = []} = props;
  const [socket] = useSocket();
  const scroller = useRef<HTMLDivElement>(null);
  const [loading, setLoading] = useSafeState(false);
  
  const [histories, setHistories] = useSafeState<ChatHistoryType[]>((() => {
    return [
      ...defaultHistory,
      ...defaultHistories
    ]
  })());

  const scrollTo = useMemoizedFn(() => {
    const div = scroller.current;
    if (div) div.scrollTop = div.scrollHeight;
  });

  const onSendMessage = useMemoizedFn((message: string) => {
    const question: ChatHistoryType = {
      id: uuid.v4(),
      isMe: true,
      messages: [{
        id: uuid.v4(),
        type: 'text',
        text: message,
        visible: true,
        prinit: false,
      }]
    }

    histories.push(question, {
      id: uuid.v4(),
      isMe: false,
      messages: []
    });

    setLoading(true);
    socket.sendMessage(message);
    setHistories([...histories]);
    requestIdleCallback(scrollTo);

    props.onSaveChat?.(question);
  });

  const onDone = useMemoizedFn((history: ChatHistoryType) => {
    setLoading(false);
    props.onSaveChat?.(history);
  });

  useEffect(() => {
    requestAnimationFrame(scrollTo);
  },[]);

  return (
    <div className={styles.chats}>
      <div className={styles.chats_history}>
        <div ref={scroller}>
          {histories.map(item => {
            return (
              <ChatHistory
                key={item.id}
                {...item}
                onDone={onDone}
                onPrinit={scrollTo}
                defaultMessages={item.messages}
              />
            );
          })}
        </div>
      </div>
      <ChatSender
        loading={loading}
        onSend={onSendMessage}
      />
    </div>
  );
}

export default Chats;